package cn.qayy.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.qayy.constants.Constant;
import cn.qayy.dto.MsgInfo;
import cn.qayy.service.Uploadable;

public class FilterData {
	/***
	 * 对list集合里的数据进行过滤
	 * @param list
	 * @return
	 * @throws Exception
	 */
	public static Map<String,List<Uploadable>> filter(List<Uploadable> list) throws Exception{
		Map<String,List<Uploadable>> map = new HashMap<String,List<Uploadable>>(Constant.SMALL_CAPACITY);
		//除去Excel里本身是重复的选项
		Set<Uploadable> set = new HashSet<Uploadable>(Constant.SMALL_CAPACITY);
		//最终容纳正确的数据 
		List<Uploadable> lastList = new ArrayList<Uploadable>(Constant.SMALL_CAPACITY);
		
		//用户上传的总记录数 
		List<Uploadable> totalCount = new ArrayList<Uploadable>(Constant.INIT_CAPACITY);
		
		if(list != null && !list.isEmpty()) {
			//用户上传的总记录数
			MsgInfo m = new MsgInfo();
			m.setErr_num((list.size()-1)+"");
			totalCount.add(m);
			map.put("totalCount", totalCount);
			
			//list里的一个对象，就是一行，num：记录行号
			int num = 0;
			for (Uploadable u : list) {
				++num;
				u.filter(map,set,num);
				//如果是错误模板，停止验证，不要再往下判断了
				if(map.get("stop") != null && !map.get("stop").isEmpty()) {
					return map;
				}
			}
			
			//存在验证不通过的情况，直接返回提示用户
			if(map.keySet().contains("fail")) {
				return map;
			}
			
			//全部验证通过
			lastList.addAll(set);
			map.put("sucess"+UUIDUtils.getCode(), lastList);
			
		}
		return map;
	}
	
	/***
	 * 过滤数据
	 * @return
	 */
	public static Map<String,List<Uploadable>> filter(Uploadable bean) throws Exception{
		Map<String,List<Uploadable>> map = new HashMap<String,List<Uploadable>>(Constant.SMALL_CAPACITY);
		/**除去Excel里本身是重复的选项**/
		Set<Uploadable> set = new HashSet<Uploadable>(Constant.SMALL_CAPACITY);
		/**最终容纳正确的数据**/
		List<Uploadable> lastList = new ArrayList<Uploadable>(Constant.SMALL_CAPACITY);
		/**记录行号，-1表示绕过标题行的判断 ，对页面来的数据进行过滤，没有Excel的标题行**/
		int num = -1;
		bean.filter(map,set,num);
		lastList.addAll(set);
		map.put("sucess"+UUIDUtils.getCode(), lastList);
		return map;
	}
}
